<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-form :inline="true" :model="formPageParam" class="user-search">
      <el-form-item label="搜索：">
        <el-input size="small" v-model="formPageParam.roleCode" placeholder="输入角色编码"></el-input>
      </el-form-item>
      <el-form-item label="">
        <el-input size="small" v-model="formPageParam.roleName" placeholder="输入角色名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="handleEdit()">添加</el-button>
      </el-form-item>
    </el-form>
    <el-table size="small" :data="listData" highlight-current-row v-loading="loading" border element-loading-text="拼命加载中" style="width: 100%;">
      <el-table-column align="center" type="selection" width="60">
      </el-table-column>
      <el-table-column sortable prop="roleCode" label="角色编码" width="120">
      </el-table-column>
      <el-table-column sortable prop="roleName" label="角色名称" width="120">
      </el-table-column>
      <el-table-column sortable prop="updateTime" label="修改时间" width="160">
        <template slot-scope="scope">
          <div>{{scope.row.updateTime|timestampToTime}}</div>
        </template>
      </el-table-column>
      <el-table-column sortable prop="updateBy" label="修改人" width="120">
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="300">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="deleteRole(scope.$index, scope.row)">删除</el-button>
          <el-button size="mini" type="success" @click="permAccess(scope.$index, scope.row)">权限</el-button>
          <el-button size="mini" type="success" @click="menuAccess(scope.$index, scope.row)">菜单</el-button>
        </template>
      </el-table-column>
    </el-table>
    <Pagination v-bind:child-msg="pageParam" @callFather="refreshFatherPage"></Pagination>
    <el-dialog :title="title" :visible.sync="editFormVisible" width="30%" @click='closeDialog("edit")'>
      <el-form label-width="120px" :model="editForm" ref="editForm" :rules="rules">
        <el-form-item label="角色编码" prop="roleCode">
          <el-input size="small" v-model="editForm.roleCode" auto-complete="off" placeholder="请输入角色编码"></el-input>
        </el-form-item>
        <el-form-item label="角色名称" prop="roleName">
          <el-input size="small" v-model="editForm.roleName" auto-complete="off" placeholder="请输入角色名称"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click='closeDialog("edit")'>取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="submitForm('editForm')">保存</el-button>
      </div>
    </el-dialog>
    <el-dialog title="菜单权限" :visible.sync="menuAccessShow" width="30%" @click='closeDialog("perm")'>
      <el-tree ref="tree" default-expand-all="" :data="rolePermissions" :props="rolePermissionProps" :default-checked-keys="checkMenu" node-key="id" show-checkbox>
      </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click='closeDialog("perm")'>取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="menuPermSave">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '../../components/Pagination'
import {getRequest, postRequest} from '../../utils/api'
export default {
  data () {
    return {
      loading: false,
      editFormVisible: false,
      menuAccessShow: false,
      title: '添加',
      editForm: {
        id: '',
        roleCode: '',
        roleName: ''
        // token: localStorage.getItem('loginToken')
      },
      rules: {
        roleCode: [
          {required: true, message: '请输入角色编码', trigger: 'blur'}
        ],
        roleName: [
          {required: true, message: '请输入角色名称', trigger: 'blur'}
        ]
      },
      formPageParam: {
        pageNum: 1,
        pageSize: 10,
        roleCode: '',
        roleName: ''
        // token: localStorage.getItem('loginToken')
      },
      listData: [],
      saveRoleId: '',
      rolePermissions: [],
      rolePermissionProps: {
        children: 'children',
        label: 'label',
        id: 'id',
        pid: 'pid'
      },
      checkMenu: [],
      pageParam: {
        currentPage: 1,
        pageSize: 10,
        total: 10
      }
    }
  },
  components: {
    Pagination
  },
  created () {
    this.getData(this.formPageParam)
  },
  methods: {
    getData (parameter) {
      this.loading = true
      getRequest('/system/role/page', parameter).then(resp => {
        this.loading = false
        if (resp && resp.code === 0 && resp.data) {
          this.listData = resp.data.records
          this.pageParam.currentPage = this.formPageParam.pageNum
          this.pageParam.pageSize = this.formPageParam.pageSize
          this.pageParam.total = resp.data.total
        }
        // eslint-disable-next-line handle-callback-err
      }).catch(err => {
        this.loading = false
        this.$message.error('获取角色列表失败，请稍后再试！')
      })
    },
    refreshFatherPage (param) {
      this.formPageParam.page = param.currentPage
      this.formPageParam.limit = param.pageSize
      this.getData(this.formPageParam)
    },
    search () {
      this.getData(this.formPageParam)
    },
    handleEdit: function (index, row) {
      this.editFormVisible = true
      if (row !== undefined && row !== 'undefined') {
        this.title = '修改'
        this.editForm.id = row.id
        this.editForm.roleCode = row.roleCode
        this.editForm.roleName = row.roleName
      } else {
        this.title = '添加'
        this.editForm.id = ''
        this.editForm.roleCode = ''
        this.editForm.roleName = ''
      }
    },
    submitForm (editData) {
      this.$refs[editData].validate(valid => {
        if (valid) {
          postRequest('/system/role/save', this.editForm).then(resp => {
            this.editFormVisible = false
            this.loading = false
            if (resp && resp.code === 0 && resp.data) {
              this.getData(this.formPageParam)
            } else {
              this.$message({
                type: 'info',
                message: resp.msg
              })
            }
            // eslint-disable-next-line handle-callback-err
          }).catch(err => {
            this.loading = false
            this.$message.error('保存角色失败，请稍后再试！')
          })
        } else {
          return false
        }
      })
    },
    deleteRole (index, row) {
      this.$confirm('确定要删除吗?', '信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let deleteParam = {'id': row.id}
        postRequest('/system/role/delete', deleteParam).then(resp => {
          if (resp && resp.code === 0 && resp.data) {
            this.$message({
              type: 'success',
              message: '角色已删除！'
            })
            this.getData(this.formPageParam)
          } else {
            this.$message({
              type: 'info',
              message: resp.msg
            })
          }
          // eslint-disable-next-line handle-callback-err
        }).catch(err => {
          this.loading = false
          this.$message.error('删除角色失败，请稍后再试！')
        })
      })
    },
    menuAccess: function (index, row) {
      this.menuAccessShow = true
      this.saveRoleId = row.id
      let roleParam = {'id': row.id}
      getRequest('/system/role/rolePermInfo', roleParam).then(resp => {
        if (resp && resp.code === 0 && resp.data) {
          this.$message({
            type: 'success',
            message: '获取角色权限成功'
          })
          this.rolePermissions = resp.data.permTree
          this.checkMenu = resp.data.checkedIds
        } else {
          this.$message({
            type: 'info',
            message: resp.msg
          })
        }
        // eslint-disable-next-line handle-callback-err
      }).catch(err => {
        this.loading = false
        this.$message.error('获取角色权限失败，请稍后再试！')
      })
    },
    permAccess: function (index, row) {
      this.menuAccessShow = true
      this.saveRoleId = row.id
      let roleParam = {'id': row.id}
      getRequest('/system/role/rolePermInfo', roleParam).then(resp => {
        if (resp && resp.code === 0 && resp.data) {
          this.$message({
            type: 'success',
            message: '获取角色权限成功'
          })
          this.rolePermissions = resp.data.permTree
          this.checkMenu = resp.data.checkedIds
        } else {
          this.$message({
            type: 'info',
            message: resp.msg
          })
        }
        // eslint-disable-next-line handle-callback-err
      }).catch(err => {
        this.loading = false
        this.$message.error('获取角色权限失败，请稍后再试！')
      })
    },
    menuPermSave () {
      let param = {
        roleId: this.saveRoleId,
        permIds: []
      }
      let node = this.$refs.tree.getCheckedNodes()
      if (node.length !== 0) {
        for (let i = 0; i < node.length; i++) {
          param.permIds.push(node[i].id)
        }
      }
      postRequest('/system/role/saveRolePerm', param).then(resp => {
        if (resp && resp.code === 0 && resp.data) {
          this.$message({
            type: 'success',
            message: '保存角色权限成功'
          })
          this.menuAccessShow = false
          this.getData(this.formPageParam)
        } else {
          this.$message({
            type: 'info',
            message: resp.msg
          })
        }
        // eslint-disable-next-line handle-callback-err
      }).catch(err => {
        this.loading = false
        this.$message.error('保存角色权限失败，请稍后再试！')
      })
    },
    closeDialog (dialog) {
      if (dialog === 'edit') {
        this.editFormVisible = false
      } else if (dialog === 'perm') {
        this.menuAccessShow = false
      }
    }
  }
}
</script>
<style scoped>
  .user-search {
    margin-top: 20px;
    text-align: left;
  }
</style>
